/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mobcatwebappgeneration;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import persistencia.controller.file.PropertyFile;
import persistencia.controller.jpa.CategoriaJpaController;
import persistencia.controller.jpa.JdbcController;
import persistencia.controller.jpa.PortalCfgJpaController;
import persistencia.controller.jpa.RegistroJpaController;
import persistencia.entidade.Categoria;
import persistencia.entidade.PortalCfg;
import persistencia.entidade.Registro;

/**
 *
 * @author Novo usuário
 */
public class BuildMobile {

    private static BuildMobile instance = new BuildMobile();
    private CategoriaJpaController catController = new CategoriaJpaController();
    private PortalCfgJpaController portalController = new PortalCfgJpaController();
    private RegistroJpaController regController = new RegistroJpaController();

    public static BuildMobile getInstance() {
        return instance;
    }

    private BuildMobile() {
    }

    public void execute(String schemaName) {

        try {
            if (schemaName != null) {
                JdbcController.getInstance().setSchema(schemaName);
            }

            File dataDir = normalizarDiretorioOutput();
            salvarPropriedadesPortal(dataDir);
            salvarCategorias( dataDir);
            salvarRegistros( dataDir);

            System.out.println("Arquivos criados com sucesso em: " + dataDir.getAbsolutePath());
        } catch (Exception ex) {
            Logger.getLogger(BuildMobile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private File normalizarDiretorioOutput() {
        String path = new File("").getAbsolutePath();
        path = path.substring(0, path.lastIndexOf("\\"));
        path += "\\MobCatCore\\src\\data";
        File dataDir = new File(path);
        if (dataDir.exists()) {
            List<File> files = Arrays.asList(dataDir.listFiles());
            for (Iterator<File> it = files.iterator(); it.hasNext();) {
                File file = it.next();
                file.delete();
            }
            dataDir.delete();
        }
        dataDir.mkdir();
        return dataDir;
    }

    private void salvarCategorias(File dataDir) {
        List<Categoria> catList = catController.findCategoriaEntities();
        String catDesc = "";
        String catDescPai = "";
        for (Iterator<Categoria> it = catList.iterator(); it.hasNext();) {
            Categoria categoria = it.next();
            saveInFile(dataDir.getAbsolutePath() + "/" + categoria.getCategoriaId() + ".cat", categoria.toMobile());
            if (categoria.getCategoriaPai() == null) {
                catDescPai += categoria.getCategoriaId() + ".cat\n";
            }
            catDesc += categoria.getCategoriaId() + ".cat\n";
        }
        saveInFile(dataDir.getAbsolutePath() + "/catRaizDesc.cfg", catDescPai);
        saveInFile(dataDir.getAbsolutePath() + "/catDesc.cfg", catDesc);
    }

    private void salvarRegistros(File dataDir) {
        List<Registro> regs = regController.findRegistroEntities();
        String regDesc = "";
        for (Iterator<Registro> it = regs.iterator(); it.hasNext();) {
            Registro registro = it.next();
            if (registro.getCategoriaCollection().size() > 0) {
                String fname = dataDir.getAbsolutePath() + "/" + registro.getRegistroId();
                saveInFile(fname + ".reg", registro.toString());
                saveImage(fname + "_reg_icone.png", registro.getIconeMob());
                saveImage(fname + "_reg_img.png", registro.getImgMob());
                regDesc += registro.getRegistroId() + ".reg\n";
            }
        }
        saveInFile(dataDir.getAbsolutePath() + "/regDesc.cfg", regDesc);
    }

    private void saveImage(String fileNome, byte[] imagem) {
        if (imagem == null) {
            return;
        }
        FileOutputStream fos = null;
        try {
            File file = new File(fileNome);
            if (file.exists()) {
                file.delete();
            }
            fos = new FileOutputStream(file);
            fos.write(imagem);
            fos.flush();
            fos.close();
        } catch (Exception ex) {
            Logger.getLogger(BuildMobile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fos.close();
            } catch (IOException ex) {
                Logger.getLogger(BuildMobile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

    private void salvarPropriedadesPortal(File dataDir) {
        PortalCfg portal = portalController.getActivePortal();
        saveImage(dataDir.getAbsolutePath() + "/icone_portal.png", portal.getIconeMob());
        saveImage(dataDir.getAbsolutePath() + "/busca_portal.png", portal.getImgBuscarMob());
        saveImage(dataDir.getAbsolutePath() + "/categoria_portal.png", portal.getImgCategoriaDefaultMob());
        saveImage(dataDir.getAbsolutePath() + "/registro_portal.png", portal.getImgRegistroDefaultMob());
        saveImage(dataDir.getAbsolutePath() + "/logo_portal.png", portal.getImgLogoMob());
        saveImage(dataDir.getAbsolutePath() + "/voltar_portal.png", portal.getImgVoltarMob());

        String s = portal.getTituloMob();
        s += "|";
        s += portal.getResumoMob();

        saveInFile(dataDir.getAbsolutePath() + "/portal.port", s);

        PropertyFile.getInstance().setNomeApp(portal.getAppNomeMob());
        PropertyFile.getInstance().setNomeExe(portal.getExeNomeMob());
    }

    private static void saveInFile(String fileName, String data) {
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            file.createNewFile();
            BufferedWriter buff = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
            buff.write(data);
            buff.flush();
            buff.close();
        } catch (IOException ex) {
            Logger.getLogger(BuildMobile.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
